<template>
  <div class="profit-container">
    <!-- 筛选条件 -->
    <div class="filter-container">
      <div class="filter-row">
        <div class="filter-group">
          <div class="filter-item">
            <el-select v-model="filterPeriod" placeholder="请选择统计周期" size="small">
              <el-option label="日" value="day" />
              <el-option label="周" value="week" />
              <el-option label="月" value="month" />
              <el-option label="年" value="year" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filterGroup" placeholder="实盘组" size="small">
              <el-option 
                v-for="group in tradingGroups" 
                :key="group.value" 
                :label="group.label" 
                :value="group.value" 
              />
            </el-select>
          </div>
          <div class="filter-item">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              size="small"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </div>
          <div class="filter-item">
            <el-select v-model="filterAccount" placeholder="账号" size="small">
              <el-option label="请选择账号" value="" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filterStrategy" placeholder="策略" size="small">
              <el-option label="全部策略" value="" />
            </el-select>
          </div>
        </div>
        <div class="action-group">
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchData">搜索</el-button>
          <el-button type="success" icon="el-icon-refresh" size="small" @click="resetFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 收益曲线图 -->
    <div class="chart-section">
      <div class="section-header">
        <div class="title">收益报表汇总</div>
      </div>
      <div class="chart-container" ref="profitChart"></div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="profitList"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="date" label="日期" width="180" />
        <el-table-column prop="realizedPnl" label="实际收益" sortable>
          <template slot-scope="scope">
            <span :class="scope.row.realizedPnl >= 0 ? 'profit-text' : 'loss-text'">
              {{ formatNumber(scope.row.realizedPnl) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="tradingVolume" label="交易额" sortable>
          <template slot-scope="scope">
            {{ formatNumber(scope.row.tradingVolume) }}
          </template>
        </el-table-column>
        <el-table-column prop="tradingCount" label="成交笔数" sortable>
          <template slot-scope="scope">
            {{ scope.row.tradingCount }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'ProfitReport',
  data() {
    return {
      // 筛选条件
      filterPeriod: 'day',
      filterGroup: '',
      dateRange: [],
      filterAccount: '',
      filterStrategy: '',

      // 日期选择器配置
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },

      // 实盘组选项
      tradingGroups: [
        { label: 'Gate.io(gate.futures)', value: 'gate.futures' },
        { label: 'Binance', value: 'binance' },
        { label: 'OKX', value: 'okx' }
      ],

      // 表格数据
      loading: false,
      profitList: [],

      // 图表实例
      chart: null,

      // 模拟数据
      mockData: {
        dates: [],
        profits: [],
        volumes: [],
        counts: []
      }
    }
  },
  methods: {
    formatNumber(num) {
      return new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(num)
    },
    initMockData() {
      // 清空之前的数据
      this.mockData = {
        dates: [],
        profits: [],
        volumes: [],
        counts: []
      }
      this.profitList = []

      // 生成最近3个月的模拟数据
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      
      let currentDate = new Date(start)
      let cumulativeProfit = 0 // 用于生成趋势性的收益数据

      while (currentDate <= end) {
        // 日期
        const dateStr = currentDate.toISOString().split('T')[0]
        this.mockData.dates.push(dateStr)
        
        // 生成趋势性的收益数据
        const dailyProfit = (Math.random() * 2000 - 800) // 偏向盈利
        cumulativeProfit += dailyProfit
        this.mockData.profits.push(cumulativeProfit)
        
        // 随机生成交易量 (10000 到 100000)
        const volume = Math.floor(Math.random() * 90000 + 10000)
        this.mockData.volumes.push(volume)
        
        // 随机生成成交笔数 (10 到 100)
        const count = Math.floor(Math.random() * 90 + 10)
        this.mockData.counts.push(count)
        
        // 生成表格数据
        this.profitList.push({
          date: dateStr,
          realizedPnl: cumulativeProfit,
          tradingVolume: volume,
          tradingCount: count
        })
        
        // 下一天
        currentDate.setDate(currentDate.getDate() + 1)
      }
    },
    initChart() {
      if (this.$refs.profitChart) {
        // 使用深色主题
        this.chart = echarts.init(this.$refs.profitChart, 'dark')
        this.updateChart()
      }
    },
    updateChart() {
      if (!this.chart) return

      const option = {
        backgroundColor: '#1f1f1f',
        title: {
          text: '收益报表汇总',
          left: 'center',
          textStyle: {
            color: '#fff'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['实际收益', '交易额', '成交笔数'],
          top: 30,
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.mockData.dates,
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          },
          axisLabel: {
            color: '#fff'
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '收益/交易额',
            position: 'left',
            axisLine: {
              lineStyle: {
                color: '#fff'
              }
            },
            axisLabel: {
              color: '#fff',
              formatter: (value) => {
                return this.formatNumber(value)
              }
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)'
              }
            }
          },
          {
            type: 'value',
            name: '成交笔数',
            position: 'right',
            axisLine: {
              lineStyle: {
                color: '#fff'
              }
            },
            axisLabel: {
              color: '#fff'
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '实际收益',
            type: 'line',
            data: this.mockData.profits,
            smooth: true,
            lineStyle: {
              color: '#67C23A',
              width: 2
            },
            itemStyle: {
              color: '#67C23A'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(103, 194, 58, 0.3)'
                },
                {
                  offset: 1,
                  color: 'rgba(103, 194, 58, 0.1)'
                }
              ])
            }
          },
          {
            name: '交易额',
            type: 'line',
            data: this.mockData.volumes,
            smooth: true,
            lineStyle: {
              color: '#409EFF',
              width: 2
            },
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '成交笔数',
            type: 'line',
            yAxisIndex: 1,
            data: this.mockData.counts,
            smooth: true,
            lineStyle: {
              color: '#E6A23C',
              width: 2
            },
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      }

      this.chart.setOption(option)
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    searchData() {
      this.loading = true
      setTimeout(() => {
        this.initMockData()
        this.updateChart()
        this.loading = false
      }, 500)
    },
    resetFilters() {
      this.filterPeriod = 'day'
      this.filterGroup = ''
      this.dateRange = []
      this.filterAccount = ''
      this.filterStrategy = ''
      this.searchData()
    }
  },
  mounted() {
    this.initMockData()
    this.$nextTick(() => {
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
    }
  }
}
</script>

<style lang="scss" scoped>
.profit-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .filter-container {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .filter-group {
        display: flex;
        gap: 8px;
        flex: 1;

        .filter-item {
          .el-select {
            width: 160px;
          }

          .el-date-editor {
            width: 240px;
          }
        }
      }

      .action-group {
        margin-left: 16px;
        white-space: nowrap;
      }
    }
  }

  .chart-section {
    background: #1f1f1f;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .section-header {
      margin-bottom: 20px;

      .title {
        font-size: 16px;
        font-weight: 500;
        color: #fff;
      }
    }

    .chart-container {
      height: 400px;
      width: 100%;
    }
  }

  .table-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .profit-text {
      color: #67C23A;
      font-weight: 500;
    }

    .loss-text {
      color: #F56C6C;
      font-weight: 500;
    }
  }
}
</style> 